<template>
  <div
    style="width: 48%; height: 320px; margin-right: auto"
    ref="chartRef"
  ></div>
</template>
<script setup lang="ts">
import {
  onMounted,
  ref,
  watch,
  nextTick,
  onBeforeUnmount,
  computed,
} from "vue";
import echarts from "@/plugins/echarts";
import type { ECOption } from '@/plugins/echarts'
import { TurnoverData } from "@/types/statistics";
const props = defineProps<{
  turnoverData: TurnoverData;
}>();
const turnoverData = ref(props.turnoverData);

// 图表dom实例
const chartRef = ref<HTMLElement | null>(null);
let resizeObserver: ResizeObserver | null = null;
let chart: echarts.ECharts;

const splitDateList = computed(() =>
  turnoverData.value.dateList ? turnoverData.value.dateList.split(",") : []
);

const splitTurnoverList = computed(() =>
  turnoverData.value.turnoverList
    ? turnoverData.value.turnoverList.split(",")
    : []
);
const initChart = () => {
  chart = echarts.init(chartRef.value, "purple-passion");
  chart.setOption<ECOption>({
    title: {
      text: "营业额统计",
      left: "10",
      top: "15",
      textStyle: {
        fontSize: "16px",
      },
    },
    legend: {
      show: true,
      orient: "horizontal",
      x: "center",
      y: "20",
      itemGap: 10,
      data: ["营业额"],
    },
    grid: {
      top: "20%",
      left: "30",
      right: "30",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: splitDateList.value,
      boundaryGap: false,
      axisLine: {
        //X轴线颜色
        lineStyle: {
          color: "#666",
          width: 1, //x轴线的宽度
        },
      },
    },
    tooltip: {
      trigger: "axis",
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "营业额",
        data: splitTurnoverList.value,
        type: "line",
        smooth: true,
        showSymbol: false,
      },
    ],
  });
  if (!resizeObserver) {
    resizeObserver = new ResizeObserver(() => {
      if (chart) {
        chart.resize();
      }
    });
    resizeObserver.observe(chartRef.value!);
  }
};
onMounted(async () => {
  await initChart();
});
onBeforeUnmount(() => {
  if (chart) {
    echarts.dispose(chart);
  }
});
watch(
  () => props.turnoverData,
  (newVal, _oldVal) => {
    nextTick(() => {
      turnoverData.value = newVal;
      echarts.dispose(chart);
      initChart();
    });
  },
  { immediate: true }
);
</script>
<style scoped lang="scss">
#main {
  background: #fff;
  border-radius: 5px;
}
</style>
